# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)

#
# WARNING: DO NOT EDIT THIS FILE MANUALLY - IT IS AUTOMATICALLY GENERATED BY THE PLUGIN
#
module SyncsHelper
  module ServerActions
    # Client call that initiates the syncing process
    # probably better to override this method and defer this processing to
    # a asynchronous task using tools as BackgroundDrb, AP4R, daemon_generate or other
    def perform_sync
      run_sync
    end

    # Allows a client to fetch a full table from the server using CSV as the
    # transport protocol
    #
    # You can define the method :dump_conditions(model_class) as the
    # syncs_controller so that extra finder conditions can be applied to the dump
    def dump
      if request.post?
        logger.info "/dump.yaml - session: #{session[:client_id]} - params: #{params.to_yaml}"
        begin
          table_name = params[:table_name]
          model_class = Module.const_get(table_name)
          # determine extra conditions
          options = {}
          if respond_to?(:dump_conditions)
            extra = dump_conditions(model_class)
            options.merge!(:conditions => extra) if extra
          end
          # dump into csv file
          tmp_file = model_class.to_csv_file(nil, options)
          begin
            # assemble the return package
            payload = File.read(tmp_file)
            package = ActsAsReplica::Structs::SyncPayload.new :payload => payload, 
              :version      => Replica.version,
              :errors       => nil,
              :total        => payload.size,
              :last_synced  => Replica.maximum('id')
          ensure
            # ensure that no csv file garbage is left behind
            File.delete(tmp_file) if File.exists?(tmp_file)
          end
          logger.info "result: #{package}" unless ENV['RAILS_ENV'] == 'production'
          render :text => compress(package.to_yaml), :content_type => 'text/plain'
        rescue => e
          logger.error "ERROR 500: #{e}"
          render :text => '', :status => 500
        end
      else
        render :text => '', :status => 404
      end
    end
    
    # Server returns the last modified records, as required by the
    # client, using the :start_id param to know where to start.
    #
    # This should not be use directly. 
    # Use the do_get_server_data action to operate over it.
    #
    # define the method :down_extra_conditions in your syncs_controller to add
    # extra finder conditions to search a restricted sub-set
    def down
      if request.post? 
        logger.info "/down.yaml - session: #{session[:client_id]} - params: #{params.to_yaml}"
        count = params[:count] == 'true'
        options = { :count => count }
        options.merge!(:extra_conditions => down_extra_conditions) if respond_to?(:down_extra_conditions)
        package = Replica.down(params[:start_id], session[:machine].machine_id, options).to_yaml
        logger.info "result: #{package}"
        render :text => compress(package), :content_type => 'text/plain'
      else
        render :text => '', :status => 404
      end
    end

    # Server receives the client's data, load them into its own database
    # and records the last time.
    #
    # This should not be used directly.
    # Use the do_send_client_data action to operate over it
    def up
      if request.post?
        # loads the models before unmarshalling the received payload
        fix_model_loading
        
        # operates over each transaction in the payload
        result = Replica.up(YAML.load(params[:syncs]), :machine_id => session[:machine].machine_id)
        
        unless result.errors and result.errors.size > 0
          # if everything went ok, stamp the clients local data with
          # the most recent timestamp that came back from the client
          # so we don't mix client and server timestamps timezones 
          # and other clock related misconfigurations
          stamp_sync_remote_user result.last_synced_id if result.last_synced_id
          render :text => compress(result.to_yaml), :status => 200
        else
          render :text => compress(result.to_yaml), :status => 500
        end
      else
        render :text => '', :status => 404
      end
    end
  end
end